<template>
  <div class="editor_container">
    <div class="editor_tools">
      <div>
        <div>B</div>
        <div>I</div>
        <!-- overline 上划线  -->
        <div style="text-decoration: underline">U</div>
        <div style="text-decoration: line-through">A</div>
      </div>
    </div>
    <div class="editor_content">
      <div
        class="editor_main"
        contenteditable
        spellcheck="false"
        @input="handleInput"
        @keydown="handleKeydown"
        ref="editorMain"
        :style="styles"
      ></div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted, useTemplateRef } from "vue";
const props = defineProps({
  modelValue: { type: String, default: "" },
  placeholder: { type: String, default: "请输入内容..." },
});
const ob = new MutationObserver((mutations, ob) => {
  console.log("change", mutations);
  for (const m of mutations) {
    if (m.target === editorMain.value) {
      // 在容器上生成 div 替换 p
      const divs = Array.from(m.addedNodes).filter((v) => v.tagName === "DIV");
      if (divs.length) {
        for (const d of divs) {
          const p = document.createElement("p");
          p.innerHTML = "<br />";
          d.after(p);
          editorMain.value.removeChild(d);
        }
      }
    }
  }
});
const emits = defineEmits(["update:modelValue"]);
const editorMain = useTemplateRef("editorMain");
const styles = computed(() => {
  return {
    "--placeholder": '"' + props.placeholder + '"',
  };
});

function handleInput(e) {
  const value = e.target.innerHTML;
  emits("update:modelValue", value);
}

function handleKeydown(e) {
  if (e.key === "Backspace" || e.keyCode === 8) {
    // 如果当前内容为空，阻止删除
    const current = editorMain.value.textContent.trim();
    if (current === "") {
      e.preventDefault();
      editorMain.value.innerHTML = "<p><br /></p>";
    }
  }
}

onMounted(() => {
  if (props.modelValue) {
    editorMain.value.innerHTML = props.modelValue;
  } else {
    const p = document.createElement("p");
    p.innerHTML = "<p><br /></p>";
    editorMain.value.appendChild(p);
  }
  ob.observe(editorMain.value, {
    childList: true,
    subtree: true,
    attributes: true,
  });
});

onUnmounted(() => {
  ob.disconnect();
});
</script>

<style scoped src="./index.css"></style>
